package com.octopus.samples.douban;

import com.octopus.core.Request;
import com.octopus.core.Response;
import com.octopus.core.parser.JsonParser;
import com.octopus.core.parser.ParseException;
import com.octopus.core.parser.ParseResult;
import com.octopus.core.result.Result;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.json.JSONObject;

/**
 * 电影分类解析
 *
 * @author shoulai.yang@gmail.com
 * @date 2019/08/02
 */
public class TagsParser extends JsonParser {

  @Override
  public ParseResult parse(JSONObject json, Response response) throws ParseException {
    Collection<String> tags = new ArrayList<>();
    List<Request> requests = new ArrayList<>();
    json.getJSONArray("tags")
        .forEach(
            tag -> {
              tags.add(tag.toString());
              int page = 0;
              String link =
                  String.format(
                      "https://movie.douban.com/j/search_subjects?type=movie&tag=%s&sort=time&page_limit=20&page_start=%s",
                      tag.toString(), page);
              requests.add(Request.me(link).extra("page", page).extra("tag", tag.toString()));
            });
    return ParseResult.me().body(Result.me().obj(tags)).requests(requests);
  }
}
